<script setup>
import { ref, onMounted } from "vue";
import { useUserStore } from "@/stores/modules/user";
import CustomTabBar from "@/components/CustomTabBar.vue";
import { refreshResume, getJobSeekerViewedCount } from "@/api/resume.js";
import { getCollectedJobCountApi } from "@/api/position.js";
import { getCandidateInterviewCountApi } from "@/api/chat.js";

const userStore = useUserStore();

// 用户信息
const userInfo = ref({
  nickname: "",
  face: "",
  description: "",
});

// 统计数据
const stats = ref({
  collect: 0, // 从API获取
  follow: 8, // 暂时写死，后续可以从API获取
  interview: 0, // 从API获取
  viewed: 0, // 从API获取
});

// 下拉刷新状态
const refreshing = ref(false);

// 获取用户信息
const getUserInfo = () => {
  const user = userStore.userInfo;
  if (user) {
    userInfo.value = {
      nickname: user.nickName || user.realName || "用户",
      face:
        user.avatar ||
        user.face ||
        user.avatarUrl ||
        "/static/images/avatar.png",
      description: user.description || "这家伙很懒,什么都没留下~",
    };
  }
};

// 跳转到设置页面
const goToSettings = () => {
  uni.navigateTo({
    url: "/pages/settings",
  });
};

// 跳转到个人信息编辑页面
const goToEditProfile = () => {
  uni.navigateTo({
    url: "/pages/candidate/editProfile",
  });
};

// 跳转到我的简历页面
const goToResume = () => {
  uni.navigateTo({
    url: "/pages/candidate/resume/resume",
  });
};

// 简历刷新功能
const handleRefreshResume = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: "刷新中...",
      mask: true,
    });

    // 调用简历刷新接口
    await refreshResume();

    // 隐藏加载提示
    uni.hideLoading();

    // 显示成功提示
    uni.showToast({
      title: "简历刷新成功",
      icon: "success",
      duration: 2000,
    });
  } catch (error) {
    // 隐藏加载提示
    uni.hideLoading();

    // 显示错误提示
    uni.showToast({
      title: error.message,
      icon: "none",
      duration: 2000,
    });
  }
};

onMounted(async () => {
  // 确保用户信息是最新的
  await userStore.getUserInfoAction();
  getUserInfo();
  // 后台获取统计数据，不阻塞页面加载
  getCollectCount();
  getViewedCount();
  getInterviewCount();
});

// 定义onShow生命周期函数
function onShow() {
  getUserInfo();
  // 每次显示页面时刷新统计数据
  getCollectCount();
  getViewedCount();
  getInterviewCount();
}

// 下拉刷新处理函数
const onPullDownRefresh = async () => {
  try {
    // 设置刷新状态
    refreshing.value = true;

    // 调用store中的getUserInfoAction获取最新用户信息
    await userStore.getUserInfoAction();

    // 更新本地用户信息显示
    getUserInfo();

    // 后台刷新统计数据，不阻塞刷新流程
    getCollectCount();
    getViewedCount();

    // 显示成功提示
    uni.showToast({
      title: "刷新成功",
      icon: "success",
      duration: 1500,
    });
  } catch (error) {
    console.error("下拉刷新失败:", error);

    // 显示错误提示
    uni.showToast({
      title: "刷新失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    // 延迟关闭刷新状态，确保动画效果
    setTimeout(() => {
      refreshing.value = false;
    }, 500);
  }
};

// 切换到招聘者角色
const switchToRecruiter = () => {
  const userStore = useUserStore();

  // 判断用户角色是否为2（招聘者和求职者）
  const userRole = userStore.userInfo?.role || 1; // 默认1表示求职者

  if (userRole !== 2) {
    // 角色不是2，提示用户需要绑定公司
    uni.showModal({
      title: "身份验证",
      content:
        "您目前身份不是招聘者，需要先绑定公司后才能成为招聘者。是否立即绑定公司？",
      success: (res) => {
        if (res.confirm) {
          // 跳转到公司绑定页面
          uni.navigateTo({
            url: "/pages/candidate/bindCompany",
          });
        }
      },
      cancelText: "取消",
      confirmText: "绑定公司",
    });
  } else {
    // 角色已经是2，直接切换
    uni.showModal({
      title: "角色切换",
      content: `您当前是求职者角色，是否要切换到招聘者角色？`,
      success: (res) => {
        if (res.confirm) {
          userStore.setUserRole("company");
          uni.showToast({
            title: "已切换到招聘者",
            duration: 1500,
          });
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/company/recommend/recommend",
            });
          }, 1500);
        }
      },
    });
  }
};

// 跳转到求职状态页面
const goToJobStatus = () => {
  uni.navigateTo({
    url: "/pages/candidate/position/jobStatus",
  });
};

// 获取收藏职位数量（后台运行，不阻塞）
const getCollectCount = () => {
  // 异步获取，不等待结果，静默失败
  getCollectedJobCountApi().then(count => {
    stats.value.collect = count || 0;
  }).catch(error => {
    // 静默失败，不显示错误信息，保持默认值0
    console.log("获取收藏数量失败，保持默认值:", error.message || error);
    stats.value.collect = 0;
  });
};

// 获取谁看过我的数量（后台运行，不阻塞）
const getViewedCount = () => {
  // 异步获取，不等待结果，静默失败
  getJobSeekerViewedCount().then(count => {
    stats.value.viewed = count || 0;
  }).catch(error => {
    // 静默失败，不显示错误信息，保持默认值0
    console.log("获取查看数量失败，保持默认值:", error.message || error);
    stats.value.viewed = 0;
  });
};

// 获取面试数量（后台运行，不阻塞）
const getInterviewCount = () => {
  // 异步获取，不等待结果，静默失败
  getCandidateInterviewCountApi().then(count => {
    stats.value.interview = count || 0;
  }).catch(error => {
    // 静默失败，不显示错误信息，保持默认值0
    console.log("获取面试数量失败，保持默认值:", error.message || error);
    stats.value.interview = 0;
  });
};

// 跳转到我的收藏页面
const goToMyCollections = () => {
  uni.navigateTo({
    url: "/pages/candidate/position/myCollections",
  });
};

// 跳转到谁看过我页面
const goToViewedByHr = () => {
  uni.navigateTo({
    url: "/pages/candidate/viewedByHr",
  });
};

// 处理附件简历功能
const handleAttachmentResume = () => {
  uni.navigateTo({
    url: "/pages/candidate/attachmentResume",
  });
};

// 跳转到面试列表页面
const goToInterviewList = () => {
  uni.navigateTo({
    url: "/pages/candidate/interview/interviewList",
  });
};
</script>

<template>
  <view class="page">
    <!-- 上部分 - 蓝色背景区域 -->
    <view class="top-section">
      <!-- 设置按钮 -->
      <view class="options">
        <image
          src="/static/icons/settings.png"
          class="settings-icon"
          @tap="goToSettings"
        ></image>
      </view>

      <!-- 头像和昵称 -->
      <view class="real-me">
        <image :src="userInfo.face" class="my-face"></image>

        <view class="my-name-wrapper">
          <view class="my-name-box">
            <text class="my-name">{{ userInfo.nickname }}</text>
          </view>
          <view class="edit-wrapper" @tap="goToResume">
            <image src="/static/icons/icon-edit.png" class="icon-edit"></image>
            <text class="edit-my-resume">我的在线简历</text>
          </view>
        </view>
      </view>

      <!-- 4个数字统计 -->
      <view class="numbers">
        <view class="num-item" @tap="goToMyCollections">
          <text class="num-counts">{{ stats.collect }}</text>
          <text class="num-text">收藏</text>
        </view>

        <view class="num-item">
          <text class="num-counts">{{ stats.follow }}</text>
          <text class="num-text">关注</text>
        </view>

        <view class="num-item" @tap="goToInterviewList">
          <text class="num-counts">{{ stats.interview }}</text>
          <text class="num-text">面试</text>
        </view>

        <view class="num-item" @tap="goToViewedByHr">
          <text class="num-counts">{{ stats.viewed }}</text>
          <text class="num-text">谁看过我</text>
        </view>
      </view>

      <!-- 中间功能box -->
      <view class="about-resume-box">
        <view class="about-resume">
          <view class="refresh-resume" @tap="handleRefreshResume">
            <image
              src="/static/icons/refresh.png"
              class="function-icon"
            ></image>
            <view class="function-text">
              <text class="about-words">简历刷新</text>
              <text class="about-words-second">优先曝光</text>
            </view>
          </view>

          <view class="attachment-resume" @tap="handleAttachmentResume">
            <image src="/static/icons/candidate/resume_attach.png" class="function-icon"></image>
            <view class="function-text">
              <text class="about-words">附件简历</text>
              <text class="about-words-second">及时更新</text>
            </view>
          </view>

          <view class="want-status" @tap="goToJobStatus">
            <image src="/static/icons/status.png" class="function-icon"></image>
            <view class="function-text">
              <text class="about-words">求职状态</text>
              <text class="about-words-second">洞悉意向</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 下部分 - 白色背景区域 -->
    <view class="bottom-section">
      <!-- 第一个功能box -->
      <view class="block-one">
        <view class="block-box">
          <view class="block-line" @tap="goToEditProfile">
            <view class="left-part">
              <image src="/static/icons/account.png" class="block-icon"></image>
              <text class="left-part-words">我的账号</text>
            </view>

            <view class="right-part">
              <text class="right-part-words">个人信息修改</text>
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line" @tap="switchToRecruiter">
            <view class="left-part">
              <image src="/static/icons/baobao.png" class="block-icon"></image>
              <text class="left-part-words">我要招人</text>
            </view>

            <view class="right-part">
              <text class="right-part-words" style="color: #31b9b3"
                >主动出击，精准匹配</text
              >
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 第二个功能box -->
      <view class="block-two">
        <view class="block-box">
          <view class="block-line">
            <view class="left-part">
              <image src="/static/icons/privacy.png" class="block-icon"></image>
              <text class="left-part-words">隐私规则</text>
            </view>

            <view class="right-part">
              <text class="right-part-words">规则明示</text>
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line">
            <view class="left-part">
              <image src="/static/icons/aboutus.png" class="block-icon"></image>
              <text class="left-part-words">关于我们</text>
            </view>

            <view class="right-part">
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line" @tap="goToSettings">
            <view class="left-part">
              <image
                src="/static/icons/settings2.png"
                class="block-icon"
              ></image>
              <text class="left-part-words">设置</text>
            </view>

            <view class="right-part">
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </view>
    <CustomTabBar :currentIndex="3" />
  </view>
</template>

<style scoped>
/* 强制覆盖uni-app页面容器的背景色，确保整个页面都是蓝色 */
:deep(.uni-page-body) {
  background-color: #00bdb4 !important;
}

:deep(.uni-page) {
  background-color: #00bdb4 !important;
}

:deep(.uni-page-wrapper) {
  background-color: #00bdb4 !important;
}

.page {
  display: flex;
  flex-direction: column;
  background-color: #00bdb4;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 上部分 - 蓝色背景区域 */
.top-section {
  background-color: #00bdb4;
  padding-top: 32px; /* 为状态栏留出空间 */
  position: relative;
}

.options {
  margin-top: 0;
  margin-right: 20px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

.settings-icon {
  width: 44rpx;
  height: 44rpx;
}

.real-me {
  margin-top: 2px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.my-face {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  margin-left: 40rpx;
}

.my-name-wrapper {
  margin-right: 40rpx;
  color: #ffffff;
  align-self: center;
  width: 55%;
}

.my-name-box {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

.my-name {
  font-size: 50rpx;
  font-weight: 500;
  color: #ffffff;
}

.edit-wrapper {
  margin-top: 4rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
}

.icon-edit {
  width: 36rpx;
  height: 36rpx;
  margin-right: 12rpx;
  filter: brightness(0) invert(1);
}

.edit-my-resume {
  font-size: 28rpx;
  color: #ffffff;
}

.numbers {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-top: 40rpx;
  margin-bottom: 80rpx; /* 为简历刷新区域留出空间，避免遮挡 */
}

.num-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.num-counts {
  font-size: 38rpx;
  font-weight: 500;
  color: #ffffff;
}

.num-text {
  font-size: 26rpx;
  font-weight: 300;
  color: #a3fdf1;
  margin-top: 4rpx;
}

.about-resume-box {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  position: absolute;
  bottom: -56rpx; /* 让简历刷新区域一半在蓝色区域，一半在白色区域 */
  left: 0;
  z-index: 10;
}

.about-resume {
  background-color: #fbf5f1;
  width: 94%;
  height: 112rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  border-radius: 32rpx;
  border: solid 1rpx #e6e6e6;
  box-sizing: border-box;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.refresh-resume,
.attachment-resume,
.want-status {
  align-self: center;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.function-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 8rpx;
}

.function-text {
  display: flex;
  flex-direction: column;
}

.about-words {
  font-size: 30rpx;
  font-weight: 800;
  color: #333333;
}

.about-words-second {
  font-size: 24rpx;
  font-weight: 300;
  color: gray;
}

/* 下部分 - 白色背景区域，填充剩余空间 */
.bottom-section {
  flex: 1;
  background-color: #f8f8f8;
  border-radius: 32rpx 32rpx 0 0;
  padding-top: 76rpx; /* 为简历刷新区域留出空间 */
  padding-bottom: 20rpx;
  min-height: calc(100vh - 258px - 32px - 120rpx);
}

.block-one {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-bottom: 60rpx;
}

.block-two {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.block-two .block-box {
  height: 320rpx;
}

.block-box {
  background-color: #ffffff;
  width: 96%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  border-radius: 20rpx;
}

.block-one .block-box {
  width: 98%;
  height: 260rpx;
}

.block-line {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 100rpx;
  align-items: center;
}

.left-part {
  align-self: center;
  margin-left: 32rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.right-part {
  align-self: center;
  margin-right: 24rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.block-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 16rpx;
}

.left-part-words {
  font-size: 32rpx;
  font-weight: 400;
  color: #333333;
}

.right-part-words {
  margin-right: 12rpx;
  font-size: 24rpx;
  font-weight: 300;
  color: gray;
}

.arrow-icon {
  width: 24rpx;
  height: 24rpx;
}
</style>
